package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.common.utils.CookieUtils;
import com.hunttown.mes.common.utils.GenFlagUtils;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.vo.SessionVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证用户是否登录（黑名单、未登录、登录过期）
 * created by wangjunfu on 2018/10/30
 */
@Service
public class LocalCheckLoginService {
    private final static Logger logger = LoggerFactory.getLogger(LocalCheckLoginService.class);

    private Cache jedisCache;
    private final AnalysisBlackListManageService blackListService;
    private final AnalysisManageManageService manageService;

    @Autowired
    public LocalCheckLoginService(AnalysisBlackListManageService blackListService, AnalysisManageManageService manageService, Cache jedisCache) {
        this.blackListService = blackListService;
        this.manageService = manageService;
        this.jedisCache = jedisCache;
    }

    /**
     * 验证用户是否登录
     * 1、黑名单是否是锁定时间内
     * 2、Cookie 是否存在
     * 3、Session/缓存是否存在
     * 4、验证 Session 是否被篡改
     *
     * @param request servlet请求
     * @return 已登录返回true，未登录返回false
     */
    public boolean checkLogin(HttpServletRequest request, HttpServletResponse response) {

        //1、黑名单是否是锁定时间内
        /* 根据需求再启用，否则增加数据的扫描压力
        String ip = IpUtils.getClientIp(request);
        boolean is_black = blackListService.checkIsBlackUser(0, 0, ip);
        if (is_black) {
            clearCookieAndSession(response, null);
            return false;
        }
        */

        //2、Cookie 是否存在
        String pin = CookieUtils.getCookieByName(request, KeyConstants.ADMIN_COOKIE);
        if (pin == null || pin.equals("")) {
            clearCookieAndSession(response, null);
            return false;
        }

        // 登录状态不对也需要重新登录
        String pin_status = CookieUtils.getCookieByName(request, KeyConstants.ADMIN_COOKIE_STATUS);
        if (!pin_status.equals("loginok")) {
            clearCookieAndSession(response, pin);
            return false;
        }

        String pin_flag = CookieUtils.getCookieByName(request, KeyConstants.ADMIN_COOKIE_FLAG);

        //3、Session 缓存是否存在（用户登录后保存一个session，若想将某人踢出登录，只要将其session移除即可）
        SessionVO vo = jedisCache.oget(KeyConstants.ADMIN_SESSION_CACHE_KEY + pin, SessionVO.class);
        if (vo == null) {
            clearCookieAndSession(response, pin);
            return false;
        }

        // 验证Flag
        if (!pin_flag.equals(vo.getPinFlag())) {
            clearCookieAndSession(response, pin);
            return false;
        }

        //4、验证 Session 是否被篡改
        AnalysisManageDTO obj = manageService.getFromCachePin(pin);

        // 生成新签名（单浏览器判定，防止多浏览器同开）
        String onlykey = CookieUtils.getCookieByName(request, KeyConstants.ADMIN_COOKIE_ONLYKEY);
        String newFlag = GenFlagUtils.genEncode(onlykey, obj.getAdminName(), obj.getPwd());
        if (!newFlag.equals(pin_flag)) {
            clearCookieAndSession(response, pin);
            return false;
        }

        return true;
    }

    /**
     * 清空Cookie 和 Session
     */
    private void clearCookieAndSession(HttpServletResponse response, String pin) {

        // 清空 Cookie，将过期时间设置为0 即可
        CookieUtils.setCookie(response, KeyConstants.ADMIN_COOKIE, "unlogin", 0);

        // 清空用户登录Session（不清空用户session）
        // jedisCache.delete(KeyConstants.ADMIN_SESSION_CACHE_KEY + pin);
    }
}
